import React, { useRef, useState } from "react";
import { Button, Space, Tabs, message } from "antd";
import CluePoolTable from "./CluePoolTable";
import { useComponentDidMount } from "@/hooks";
import { fetchClueTabNum, importClueList, receiveClueCompany } from '../services';
import ClueImport from "../modals/ClueImport";
import { PlusOutlined } from "@ant-design/icons";
import { useRequest } from "ahooks";
import ThrottleButton from "@/components/ThrottleButton";
import { getStorage } from "@/utils/storage";
import PermissionBtn from "@/components/PermissionBtn";
import ClueReceive from "../ClueReceive";
import { clueCompanyTypes } from "@/constants/types";

// 切换tab需要刷新的tab
const tabChangeShouldUpdateTab = ['all', 'claimedNum'];


const PreOrder = () => {
  const allRef = useRef();
  const waitClaimNumRef = useRef();
  const claimedNumRef = useRef();
  // 用户信息
  const userInfo = getStorage('userInfo');
  const tabArr = [
    {
      key: 'all',
      auth: 'crm:clues:list:total',
    },
    {
      key: 'waitClaimNum',
      auth: 'crm:clues:list:unclaimed',
    },
    {
      key: 'claimedNum',
      auth: 'crm:clues:list:claimed',
    },
  ];
  const currTab = tabArr.find(v => userInfo?.functions?.includes(v?.auth))
  const [activeKey, setActiveKey] = useState<string>(currTab?.key || 'all');

  const [tabNum, setTabNum] = useState<any>({all: 0, authed: 0, waitOrder: 0, ordered: 0, canceled: 0});
  // 导入线索
  const [visible, setVisible] = useState(false);
  const {loading: importLoading, runAsync: importClueListApi} = useRequest(importClueList, {manual: true});
  // 领取
  const [receiveVisible, setReceiveVisible] = useState(false);
  const {loading: receiveLoading, runAsync: receiveClueCompanyApi} = useRequest(receiveClueCompany, {manual: true});

  const fetchTabNum = async () => {
    const res = await fetchClueTabNum();
    setTabNum({
      all: res?.total || 0,
      waitClaimNum: res?.waitClaimNum || 0,
      claimedNum: res?.claimedNum || 0,
    });
  }


  const tabChange = (key: string) => {
    setActiveKey(key);  
  }

  const refreshNum = () => {
    fetchTabNum();
  }

  const search = () => {
    setTimeout(() => {
      const refObj = tabList.find(v => v.key === activeKey)?.comRef;
      refObj?.current?.refreshTable();
    }, 0)
  }

  const clueImportProps = {
    visible,
    title: '批量导入线索客户',
    loading: importLoading,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await importClueListApi(params);
      if (res?.code === '0') {
        clueImportProps.onCancel();
        message.success('导入成功!');
        search();
      }
    }
  }

  const childrenProps: {refreshNum: any; activeKey: string;} = {
    refreshNum,
    activeKey,
  }
  
  const removeRow = (record: clueCompanyTypes) => {
    setTimeout(() => {
      const refObj = tabList.find(v => v.key === activeKey)?.comRef;
      refObj?.current?.removeRow(record);
    }, 0)
  }

  // 认领客户
  const clueReceiveProps = {
    visible: receiveVisible,
    loading: receiveLoading,
    title: '客户认领',
    onCancel: () => {
      setReceiveVisible(false);
    },
    onSubmit: (record: clueCompanyTypes) => {
      receiveClueCompanyApi({id: record?.id}).then(
        res => {
          if (res?.code === '0') {
            message.success('认领成功!');
            clueReceiveProps.onCancel();
            removeRow(record);
            refreshNum();
          }
        }
      );
    }
  }

  const handleReceive = () => {
    setReceiveVisible(true);
  }
  const handleImport = () => {
    setVisible(true);
  }



  const tabList: Array<any> = [
    {
      title: '全部',
      key: 'all',
      auth: 'crm:clues:list:total',
      label: tabNum?.all > 0 ? `全部 ( ${ tabNum?.all} )` : '全部',
      comRef: allRef,
      children: <CluePoolTable {...childrenProps} tabKey="all" tabChangeShouldUpdateTab={tabChangeShouldUpdateTab} ref={allRef} />,
    },
    {
      title: '待认领',
      key: 'waitClaimNum',
      auth: 'crm:clues:list:unclaimed',
      label: tabNum?.waitClaimNum > 0 ? `待认领 ( ${ tabNum?.waitClaimNum} )` : '待认领',
      comRef: waitClaimNumRef,
      children: <CluePoolTable {...childrenProps} tabKey="waitClaimNum" tabChangeShouldUpdateTab={tabChangeShouldUpdateTab} ref={waitClaimNumRef} />,
    },
    {
      title: '已认领',
      key: 'claimedNum',
      auth: 'crm:clues:list:claimed',
      label: tabNum?.claimedNum > 0 ? `已认领 ( ${ tabNum?.claimedNum} )` : '已认领',
      comRef: claimedNumRef,
      children: <CluePoolTable {...childrenProps} tabKey="claimedNum" tabChangeShouldUpdateTab={tabChangeShouldUpdateTab} ref={claimedNumRef} />,
    }
  ];

  const composeTabList = () => {
    if (!userInfo?.functions?.length) {
      return [];
    }
    return tabList.filter(v => userInfo?.functions?.includes(v?.auth));
  }


  useComponentDidMount(() => {
    fetchTabNum();
  });
  
  return (
    <>
      <Tabs
        activeKey={activeKey}
        onChange={tabChange}
        tabBarExtraContent={{
          right: (
            <Space>
             <ThrottleButton onClick={search} title="刷新列表" />
              {activeKey === 'waitClaimNum' && <Button type="primary" onClick={handleReceive}><PlusOutlined/>认领客户</Button>}
              {activeKey === 'all' && <PermissionBtn id="crm:clues:importClues" type="primary" onClick={handleImport}><PlusOutlined/>批量导入线索</PermissionBtn>}
            </Space>
          )
        }} 
        items={composeTabList()}
      />
      {visible && <ClueImport {...clueImportProps} />}
      {receiveVisible && <ClueReceive {...clueReceiveProps} />} 
    </>
  );
};


export default PreOrder;